package net.wangds.dymodel.query;

import net.wangds.dymodel.ddl.DyModelDdlComp;
import net.wangds.dymodel.meta.entity.DyModelDefEntity;
import net.wangds.dymodel.utls.DynamicModelUtils;
import net.wangds.jdbc.comp.jdbc.JdbcComp;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * .
 * <p></p>
 *
 * @author 王东石 2021/2/16 10:31.
 */
@Component
@SuppressWarnings("unused")
public class UpdateParse {

    @Autowired
    private DyModelDdlComp mmCmpDdl;

    @Autowired
    private QueryParse mmCmpQuery;

    @Autowired
    private InsertParse mmCmpIns;

    @Autowired
    private JdbcComp mmJdbc;


    /**
     * 更新.
     * @param obj 更新对象.
     * @param model 模型.
     * @param <T> 对象类型.
     * @return 更新后对象.
     */
    @SuppressWarnings("unchecked")
    public <T> T update(T obj, DyModelDefEntity model){

        if(obj==null){
            return null;
        }

        String id = (String)DynamicModelUtils.fetchFieldVal(obj, "id");
        if(StringUtils.isBlank(id)||!mmCmpQuery.existsById(id, model)){
            return mmCmpIns.insert(obj, model);
        }

        List<Object> args = new ArrayList<>();
        StringBuffer sb = new StringBuffer("UPDATE ")
                .append(DynamicModelUtils.toFullTableName(model))
                .append(" SET ");


        mmCmpDdl.foreachField(model, (f)->{
            sb.append(" ").append(DynamicModelUtils.toColumnName(f)).append("=?,");
            args.add(DynamicModelUtils.fetchFieldVal(obj, f));
        });

        if(StringUtils.endsWith(sb, ",")){
            sb.deleteCharAt(sb.length()-1);
        }
        sb.append(" WHERE `id`=?");
        args.add(DynamicModelUtils.fetchFieldVal(obj, "id"));

        Object[] objs = new Object[args.size()];
        mmJdbc.executeUpdate(sb.toString(), args.toArray(objs));

        return mmCmpQuery.findById(id, model, (Class<T>)obj.getClass());
    }

}
